package com.xy6.deepjvm.chapter03;

/**
 * 指令重排示例
 * 输出结果：
 * true 1 0
 * true 1 1
 * true 0 0
 * false 0 0
 * false 1 0
 * 
 * @author zhang
 * @since 2018-05-22
 */
public class JmmReorder {

	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 1000; i++) {
			RecordExample record = new RecordExample();
			Thread t1 = new Thread(new RecordThread1(record));
			Thread t2 = new Thread(new RecordThread2(record));
			t1.start();
			t2.start();
			t1.join();
			t2.join();
		}
	}

	static class RecordThread1 implements Runnable {
		private RecordExample record;

		public RecordThread1(RecordExample record) {
			this.record = record;
		}

		@Override
		public void run() {
			record.write();
		}
	}

	static class RecordThread2 implements Runnable {
		private RecordExample record;

		public RecordThread2(RecordExample record) {
			this.record = record;
		}

		@Override
		public void run() {
			record.read();
		}
	}

	static class RecordExample {
		int a = 0;
		volatile boolean flag = false;

		public void write() {
			a = 1;
			flag = true;
		}

		public void read() {
			int i = 0;
			if (flag) {
				i = a * a;
			}
			// 该代码可证明存在true 0 0情况
//			if(flag && a == 0){
//			}
			System.out.println(String.format("flag:%s, a:%d, i:%d", String.valueOf(flag), a, i));
		}
	}

}
